package com.hzmg.route.akka;

import akka.actor.typed.ActorRef;
import akka.actor.typed.ActorSystem;
import akka.actor.typed.Scheduler;
import akka.actor.typed.javadsl.AskPattern;
import akka.http.javadsl.server.PathMatchers;
import akka.japi.function.Function;
import com.hzmg.route.akka.msg.MsgDemo;
import com.hzmg.support.Command;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.Duration;
import java.util.concurrent.CompletionStage;

import static akka.http.javadsl.server.Directives.*;


public class Route {
    private static final Logger logger = LoggerFactory.getLogger(Route.class);

    private final ActorRef<Command> actorRef;
    private final Duration askTimeout;
    private final Scheduler scheduler;


    public Route(ActorSystem<?> system, ActorRef<Command> actorRef) {
        this.actorRef = actorRef;
        askTimeout = system.settings().config().getDuration("my-app.routes.ask-timeout");
        scheduler = system.scheduler();
    }

    public CompletionStage<String> showMsg(String msg) {
        return AskPattern.ask(actorRef, new Function<ActorRef<String>, Command>() {
            @Override
            public Command apply(ActorRef<String> param) throws Exception {
                logger.info("sender: {}", actorRef, param);
                return new MsgDemo(param);
            }
        }, askTimeout, scheduler);
    }

    public CompletionStage<String> showMsg() {
        return AskPattern.ask(actorRef, MsgDemo::new, askTimeout, scheduler);
    }

    public akka.http.javadsl.server.Route RouteDemo() {
        return pathPrefix("demo", () ->
                extractRequest(ctx -> {
                    concat(
                            path(PathMatchers.segment(), (String msg) -> concat(
                                    get(() -> onSuccess(showMsg(msg), performed -> {
                                        System.out.println(PathMatchers.segment().toString());
                                        return complete("nice!!");
                                    }))
                            ))
                    );
                    return complete("last nice!!");
                }));
    }
}
